package com.xdxc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xdxc.mapper.SubjectMapper;
import com.xdxc.model.entity.Subject;
import com.xdxc.service.SubjectService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public List<Subject> getSubjectTree() {
        // 1. 查询所有科目数据
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("sort");
        List<Subject> allSubjects = baseMapper.selectList(wrapper);

        // 2. 构建树形结构
        return buildSubjectTree(allSubjects);
    }

    /**
     * 构建科目树形结构
     * @param allSubjects 所有科目列表
     * @return 树形结构的科目列表
     */
    private List<Subject> buildSubjectTree(List<Subject> allSubjects) {
        // 存储顶级科目(父ID为0的科目)
        List<Subject> rootSubjects = new ArrayList<>();

        // 使用Map存储所有科目，key为科目ID
        Map<Long, Subject> subjectMap = new HashMap<>();
        for (Subject subject : allSubjects) {
            subjectMap.put(subject.getId(), subject);
        }

        // 遍历所有科目，构建父子关系
        for (Subject subject : allSubjects) {
            Long parentId = subject.getParentId();
            if (parentId == null || parentId == 0) {
                // 父ID为0或null的是顶级科目
                rootSubjects.add(subject);
            } else {
                // 找到父科目并添加到其children列表中
                Subject parent = subjectMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(subject);
                }
            }
        }

        return rootSubjects;
    }
}